<template>
  <div class="mobile-work-order-edit">
    <!-- 移动端头部 -->
    <div class="mobile-header">
      <el-button 
        link 
        @click="$router.back()"
        class="back-button"
      >
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h3>编辑工单</h3>
      <el-button 
        type="primary" 
        size="small"
        @click="saveWorkOrder" 
        :loading="saving"
      >
        保存
      </el-button>
    </div>

    <!-- 表单内容 -->
    <div class="form-content" v-loading="loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="mobile-form"
      >


        <!-- 详细信息卡片 -->
        <div class="form-card">
          <div class="card-title">详细信息</div>
          
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入工单描述"
              show-word-limit
              maxlength="500"
            />
          </el-form-item>

          <el-form-item label="区域">
            <el-select v-model="form.area_id" placeholder="请选择区域" style="width: 100%" clearable>
              <el-option
                v-for="area in areas"
                :key="area.value"
                :label="area.label"
                :value="area.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="form.notes"
              type="textarea"
              :rows="3"
              placeholder="请输入备注（可选）"
              show-word-limit
              maxlength="300"
            />
          </el-form-item>
        </div>

        <!-- 自定义字段卡片 -->
        <div v-if="customFields.length > 0" class="form-card">
          <div class="card-title">自定义字段</div>
          
          <div v-for="field in customFields" :key="field.id">
            <!-- 文本输入 -->
            <el-form-item v-if="field.field_type === 'text'" :label="field.label">
              <el-input
                v-model="customFieldValues[field.name]"
                :placeholder="`请输入${field.label}`"
                clearable
              />
            </el-form-item>

            <!-- 数字输入 -->
            <el-form-item v-else-if="field.field_type === 'number'" :label="field.label">
              <el-input-number
                v-model="customFieldValues[field.name]"
                :placeholder="`请输入${field.label}`"
                style="width: 100%"
                controls-position="right"
              />
            </el-form-item>

            <!-- 日期选择 -->
            <el-form-item v-else-if="field.field_type === 'date'" :label="field.label">
              <el-date-picker
                v-model="customFieldValues[field.name]"
                type="date"
                :placeholder="`请选择${field.label}`"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 日期时间选择 -->
            <el-form-item v-else-if="field.field_type === 'datetime'" :label="field.label">
              <el-date-picker
                v-model="customFieldValues[field.name]"
                type="datetime"
                :placeholder="`请选择${field.label}`"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 单选 -->
            <el-form-item v-else-if="field.field_type === 'select'" :label="field.label">
              <el-select
                v-model="customFieldValues[field.name]"
                :placeholder="`请选择${field.label}`"
                style="width: 100%"
              >
                <el-option
                  v-for="option in field.options"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>

            <!-- 多选 -->
            <el-form-item v-else-if="field.field_type === 'checkbox'" :label="field.label">
              <el-checkbox-group v-model="customFieldValues[field.name]" class="mobile-checkbox-group">
                <el-checkbox
                  v-for="option in field.options"
                  :key="option"
                  :label="option"
                  :value="option"
                  class="mobile-checkbox"
                >
                  {{ option }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </div>
        
        <!-- 操作按钮区域 -->
        <div class="form-card">
          <div class="card-title">操作</div>
          <!-- 完成工单和材料录入按钮并排排列 -->
          <div class="button-row">
            <el-button 
              type="warning" 
              size="large"
              @click="showCompleteDialog"
              style="flex: 1; margin-right: 8px;"
            >
              完成工单
            </el-button>
            <el-button 
              type="info" 
              size="large"
              @click="openMaterialDialog"
              style="flex: 1;"
            >
              材料录入
            </el-button>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 材料录入对话框 -->
    <el-dialog 
      v-model="materialDialogVisible" 
      title="材料录入" 
      width="90%"
      :before-close="closeMaterialDialog"
    >
      <div class="material-section">
        <div class="section-title">选择材料</div>
        <el-form :model="materialForm" label-width="80px">
          <el-form-item label="材料">
            <el-select
              v-model="materialForm.material_id"
              placeholder="请选择材料"
              filterable
              style="width: 100%"
              @change="onMaterialSelect"
            >
              <el-option
                v-for="material in availableMaterials"
                :key="material.id"
                :label="`${material.name} (${material.code})`"
                :value="material.id"
              >
                <div style="display: flex; justify-content: space-between;">
                  <span>{{ material.name }}</span>
                  <span style="color: #999; font-size: 12px;">库存: {{ material.stock_quantity }} {{ material.unit }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number
              v-model="materialForm.quantity"
              :min="1"
              :max="selectedMaterial?.stock_quantity || 999999"
              placeholder="请输入数量"
              style="width: 100%"
            />
          </el-form-item>
          <el-button 
            type="primary" 
            @click="addMaterialToList" 
            :disabled="!materialForm.material_id || !materialForm.quantity"
            style="width: 100%; margin-top: 12px;"
          >
            添加至清单
          </el-button>
        </el-form>
      </div>
      
      <!-- 已录入材料列表 -->
      <div class="material-list" v-if="usedMaterials.length > 0">
        <div class="section-title">已录入材料</div>
        <div class="used-material-item" v-for="material in usedMaterials" :key="material.id">
          <div class="material-info">
            <div class="material-name">{{ material.material_name }}</div>
            <div class="material-details">
              <span class="material-quantity">{{ material.quantity }} {{ material.unit || '个' }}</span>
              <span class="material-date">{{ formatDate(material.usage_date) }}</span>
            </div>
            <div class="material-purpose">{{ material.purpose }}</div>
          </div>
          <el-button type="danger" size="small" @click="deleteUsedMaterial(material.id)">删除</el-button>
        </div>
      </div>
      
      <div class="material-list" v-if="materialsToAdd.length > 0">
        <div class="section-title">待录入材料</div>
        <div class="material-item" v-for="(material, index) in materialsToAdd" :key="index">
          <div class="material-info">
            <div class="material-name">{{ material.name }}</div>
            <div class="material-spec">{{ material.specification }}</div>
            <div class="material-quantity">{{ material.quantity }} {{ material.unit }}</div>
          </div>
          <el-button type="danger" size="small" @click="removeMaterialFromList(index)">删除</el-button>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="closeMaterialDialog">取消</el-button>
        <el-button type="primary" @click="submitMaterialUsage" :disabled="materialsToAdd.length === 0">确定录入</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { workOrdersApi, usersApi, areasApi } from '@/api'

import { materialsApi } from '@/api'
import { materialUsageApi } from '@/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

// 用户列表
const users = ref([])

// 区域列表
const areas = ref([])

// 自定义字段
const customFields = ref([])
const customFieldValues = ref({})

// 材料录入相关
const materialDialogVisible = ref(false)
const availableMaterials = ref([])
const materialsToAdd = ref([])
const usedMaterials = ref([])
const selectedMaterial = ref(null)
const materialForm = reactive({
  material_id: '',
  quantity: 1
})

// 完成工单相关（保留completeForm以防其他地方使用）
const completeForm = reactive({
  work_order_id: null,
  description: '',
  fault_category: ''
})

// 表单数据
const form = reactive({
  title: '',
  description: '',
  type: '',
  status: '',
  priority: '',
  assignee: '',
  area_id: '',
  location: '',
  expected_completion: '',
  notes: ''
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入工单描述', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  assignee: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ],
  expected_completion: [
    { required: true, message: '请选择预计完成时间', trigger: 'change' }
  ]
}

// 加载工单详情
const loadWorkOrder = async () => {
  loading.value = true
  try {
    const id = route.params.id
    const response = await workOrdersApi.getWorkOrder(id)
    const workOrder = response.data.work_order
    
    // 填充表单数据
    Object.assign(form, {
      title: workOrder.title,
      description: workOrder.description,
      type: workOrder.type,
      status: workOrder.status,
      priority: workOrder.priority,
      assignee: workOrder.assignee_id,
      area_id: workOrder.area_id,
      location: workOrder.location,
      expected_completion: workOrder.scheduled_end,
      notes: workOrder.notes || ''
    })
    
    // 处理自定义字段数据
    const customFieldsData = workOrder.custom_fields || {}
    const processedCustomFields = {}
    
    Object.keys(customFieldsData).forEach(fieldName => {
      const fieldData = customFieldsData[fieldName]
      let value
      
      // 如果fieldData是对象且有value属性
      if (fieldData && typeof fieldData === 'object' && fieldData.value !== undefined) {
        value = fieldData.value
      } else {
        // 否则直接使用fieldData作为值
        value = fieldData
      }
      
      // 处理字符串格式的数组，如 "['掉线']"
      if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) {
        try {
          value = JSON.parse(value.replace(/'/g, '"'))
        } catch (e) {
          console.warn('Failed to parse custom field array string:', value)
          // 解析失败时保持原值
        }
      }
      
      // 处理其他JSON字符串
      if (typeof value === 'string') {
        try {
          const parsed = JSON.parse(value)
          if (Array.isArray(parsed) || (parsed && typeof parsed === 'object')) {
            value = parsed
          }
        } catch (e) {
          // 不是JSON格式，保持原值
        }
      }
      
      processedCustomFields[fieldName] = value
    })
    
    customFieldValues.value = processedCustomFields
  } catch (error) {
    console.error('加载工单详情失败:', error)
    ElMessage.error('加载工单详情失败')
  } finally {
    loading.value = false
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const response = await usersApi.getUsers({ per_page: 100 })
    users.value = response.data.users || response.data || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

// 加载区域列表
const loadAreas = async () => {
  try {
    const response = await areasApi.getAreaOptions()
    areas.value = response.data || []
  } catch (error) {
    console.error('加载区域列表失败:', error)
    ElMessage.error('加载区域列表失败')
  }
}

// 加载自定义字段
const loadCustomFields = async () => {
  try {
    const response = await workOrdersApi.getCustomFields()
    customFields.value = response.data.fields
    
    // 初始化自定义字段值
    customFields.value.forEach(field => {
      if (!(field.name in customFieldValues.value)) {
        if (field.field_type === 'checkbox') {
          customFieldValues.value[field.name] = []
        } else {
          customFieldValues.value[field.name] = ''
        }
      }
    })
  } catch (error) {
    console.error('加载自定义字段失败:', error)
  }
}

// 保存工单
const saveWorkOrder = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    const id = route.params.id
    const updateData = {
      ...form,
      assignee_id: form.assignee,
      scheduled_end: form.expected_completion,
      custom_fields: customFieldValues.value
    }
    
    // 删除前端字段，避免传递无效字段
    delete updateData.expected_completion
    delete updateData.assignee
    
    await workOrdersApi.updateWorkOrder(id, updateData)
    
    ElMessage.success('工单更新成功')
    router.push(`/mobile/work-orders/${id}`)
  } catch (error) {
    console.error('保存工单失败:', error)
    ElMessage.error('保存工单失败')
  } finally {
    saving.value = false
  }
}

// 加载材料列表
const loadMaterials = async () => {
  try {
    const response = await materialsApi.getMaterials({ page: 1, per_page: 100 })
    availableMaterials.value = response.data.materials || response.data || []
  } catch (error) {
    console.error('加载材料列表失败:', error)
    ElMessage.error('加载材料列表失败')
  }
}

// 加载已录入材料
const loadUsedMaterials = async () => {
  try {
    const workOrderId = route.params.id
    const response = await workOrdersApi.getWorkOrderMaterials(workOrderId)
    usedMaterials.value = response.data.materials || []
  } catch (error) {
    console.error('加载已录入材料失败:', error)
    ElMessage.error('加载已录入材料失败')
  }
}

// 删除已录入材料
const deleteUsedMaterial = async (materialId) => {
  try {
    await workOrdersApi.deleteMaterialUsage(materialId)
    ElMessage.success('删除成功')
    loadUsedMaterials() // 重新加载列表
  } catch (error) {
    console.error('删除材料失败:', error)
    ElMessage.error('删除材料失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 打开材料录入对话框
const openMaterialDialog = () => {
  materialDialogVisible.value = true
  loadMaterials()
  loadUsedMaterials()
}

// 关闭材料录入对话框
const closeMaterialDialog = () => {
  materialDialogVisible.value = false
  materialForm.material_id = ''
  materialForm.quantity = 1
  selectedMaterial.value = null
  materialsToAdd.value = []
}

// 选择材料时的处理
const onMaterialSelect = (materialId) => {
  selectedMaterial.value = availableMaterials.value.find(m => m.id === materialId)
}

// 添加材料到清单
const addMaterialToList = () => {
  if (!selectedMaterial.value || !materialForm.quantity) {
    ElMessage.warning('请选择材料并输入数量')
    return
  }

  const existingIndex = materialsToAdd.value.findIndex(m => m.id === selectedMaterial.value.id)
  if (existingIndex >= 0) {
    materialsToAdd.value[existingIndex].quantity += materialForm.quantity
  } else {
    materialsToAdd.value.push({
      id: selectedMaterial.value.id,
      name: selectedMaterial.value.name,
      specification: selectedMaterial.value.specification,
      unit: selectedMaterial.value.unit,
      quantity: materialForm.quantity
    })
  }

  // 重置表单
  materialForm.material_id = ''
  materialForm.quantity = 1
  selectedMaterial.value = null
}

// 从清单中移除材料
const removeMaterialFromList = (index) => {
  materialsToAdd.value.splice(index, 1)
}

// 提交材料使用记录
const submitMaterialUsage = async () => {
  if (materialsToAdd.value.length === 0) {
    ElMessage.warning('请至少添加一个材料')
    return
  }

  try {
    const workOrderId = route.params.id
    for (const material of materialsToAdd.value) {
      await materialUsageApi.createUsageRecord({
        work_order_id: workOrderId,
        material_id: material.id,
        quantity: material.quantity,
        usage_type: '工单使用',
        user_name: '当前用户',
        usage_date: new Date().toISOString().split('T')[0], // 格式化为YYYY-MM-DD
        purpose: `工单编辑页面录入 - ${material.name}`,
        notes: `工单编辑页面录入 - ${material.name}`
      })
    }
    
    ElMessage.success('材料录入成功')
    loadUsedMaterials() // 重新加载已录入材料列表
    closeMaterialDialog()
  } catch (error) {
    console.error('材料录入失败:', error)
    ElMessage.error('材料录入失败')
  }
}

// 完成工单相关方法
const showCompleteDialog = async () => {
  try {
    const workOrderId = route.params.id
    // 直接完成工单，不显示弹窗
    await workOrdersApi.updateWorkOrder(workOrderId, {
      status: 'completed',
      actual_end: new Date().toISOString(),
      custom_fields: {
        fault_category: 'other',
        completion_description: '工单已完成'
      }
    })
    
    ElMessage.success('工单完成成功')
    router.push('/mobile/maintenance')
  } catch (error) {
    console.error('完成工单失败:', error)
    ElMessage.error('完成工单失败')
  }
}

const submitComplete = async () => {
  // 保留原方法以防其他地方调用
  if (!completeForm.description.trim()) {
    ElMessage.error('请填写完成描述')
    return
  }
  
  try {
    // 更新工单状态
    await workOrdersApi.updateWorkOrder(completeForm.work_order_id, {
      status: 'completed',
      actual_end: new Date().toISOString(),
      custom_fields: {
        fault_category: completeForm.fault_category,
        completion_description: completeForm.description
      }
    })
    
    ElMessage.success('工单完成成功')
    closeCompleteDialog()
    router.push('/mobile/maintenance')
  } catch (error) {
    console.error('完成工单失败:', error)
    ElMessage.error('完成工单失败')
  }
}

const closeCompleteDialog = () => {
  completeDialogVisible.value = false
  completeForm.work_order_id = null
  completeForm.description = ''
  completeForm.fault_category = ''
}

onMounted(async () => {
  // 移除loadUsers()调用，因为普通用户无法访问用户列表接口
  // loadUsers()
  loadAreas()
  await loadCustomFields()
  loadWorkOrder()
})
</script>

<style scoped>
.mobile-work-order-edit {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.mobile-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  flex: 1;
  text-align: center;
}

.back-button {
  padding: 8px;
  margin-left: -8px;
  color: #409eff;
}

.form-content {
  padding: 16px;
}

.form-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.mobile-form {
  width: 100%;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form .el-form-item__label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.4;
}

.mobile-form .el-input__inner,
.mobile-form .el-textarea__inner {
  font-size: 16px;
  border-radius: 6px;
}

.mobile-form .el-select {
  width: 100%;
}

.mobile-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.mobile-checkbox {
  margin-right: 0;
  margin-bottom: 0;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.mobile-checkbox:last-child {
  border-bottom: none;
}

.button-row {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

/* 材料录入相关样式 */
.material-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.material-list {
  margin-top: 20px;
}

.material-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 8px;
}

.material-info {
  flex: 1;
}

.material-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.material-spec {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.material-quantity {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.used-material-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  margin-bottom: 8px;
  border-left: 3px solid #409eff;
}

.material-details {
  display: flex;
  gap: 12px;
  margin: 4px 0;
}

.material-date {
  font-size: 12px;
  color: #909399;
}

.material-purpose {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .mobile-header {
    padding: 10px 12px;
  }
  
  .form-content {
    padding: 12px;
  }
  
  .form-card {
    padding: 12px;
    margin-bottom: 12px;
  }
  
  .card-title {
    font-size: 15px;
    margin-bottom: 12px;
  }
  
  .material-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .material-item .el-button {
    align-self: flex-end;
  }
}
</style>